<!doctype html>
<html lang="en">
  <head>
    <title>Canvas</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body,
      html {
        padding: 0;
        margin: 0;
      }
      #canvas {
        margin: 10px;
        box-shadow: 4px 4px 12px rgba(0, 0, 0, 0.5);
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script src="utils.js"></script>
    <script src="Ball.js"></script>
    <script>
      const canvas = C.$("#canvas");
      const ctx = canvas.getContext("2d");

      const W = (canvas.width = 600);
      const H = (canvas.height = 600);

      const ball = new Ball({
        x: 0,
        y: 0,
        r: 50,
        vx: (Math.random() - 0.5) * 3,
        vy: (Math.random() - 0.5) * 3,
      }).render(ctx);

      const mouse = C.getOffset(canvas);
      const speed = 3;
      const a = 0.1;

      function move() {
        ctx.clearRect(0, 0, W, H);

        const dx = mouse.x - ball.x;
        const dy = mouse.y - ball.y;

        // 角度
        const angle = Math.atan2(dy, dx);

        // 速度分解在 X, Y 方向
        ball.vx = speed * Math.cos(angle);
        ball.vy = speed * Math.sin(angle);

        ball.x += ball.vx;
        ball.y += ball.vy;

        // 加速度分解在 X, Y 方向
        const ax = a * Math.cos(angle);
        const ay = a * Math.sin(angle);

        ball.vx += ax;
        ball.vy += ay;

        ball.render(ctx);
        requestAnimationFrame(move);
      }
      requestAnimationFrame(move);
    </script>
  </body>
</html>
